package com.xiaoxing.utils;

import com.xiaoxing.domain.entity.LoginUser;
import com.xiaoxing.domain.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 *  SpringSecurity的工具类
 *
 * @author 李芋钢
 * @since 2023-01-12
 */
//工具类
public class SecurityUtils
{
    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser()
    {
        Authentication authentication = getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof LoginUser) {
                return (LoginUser) principal;
            }
        }
        return null;
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static Boolean isAdmin(){
        Long id = getLoginUser().getUser().getId();
        return id != null && id.equals(1L);
    }

    public static Long getUserId() {
        LoginUser loginUser = getLoginUser();
        if (loginUser != null) {
            User user = loginUser.getUser();
            if (user != null) {
                return user.getId();
            }
        }
        return null;
    }

}
